import * as step from '@flow-step/step-toolkit'
import process from 'process'
import {getParams, IParams} from './params'
import axios from 'axios';


async function runStep(): Promise<void> {

    const params = getParams()
    step.infoV1(`PIPELINE_ID=${params.pipelineID}`)
    step.infoV1(`PIPELINE_NAME=${params.pipelineName}`)
    step.infoV1(`BUILD_NUMBER=${params.buildNumber}`)
    step.infoV1(`WORK_SPACE=${params.workSpace}`)
    step.infoV1(`PROJECT_DIR=${params.projectDir}`)
    step.infoV1(`BUILD_JOB_ID=${params.buildJobID}`)
    step.infoV1(`APPSTACK_CLOUD_ROLLOUT_TOKEN=${params.appStackCloudRolloutToken}`)
    step.infoV1(`APPSTACK_ORG_ID=${params.appStackOrgId}`)
    step.infoV1(`APPSTACK_CLOUD_ROLLOUT_TIMESTAMP=${params.appStackCloudRolloutTimeStamp}`)
    step.infoV1(`EMPLOYEE_ID=${params.appStackUserId}`)
    step.infoV1(`DOMAIN=${params.appStackDomain}`)
    step.infoV1(`COOKIE=${params.appStackCookie}`)

    const response = await axios.post(`${params.appStackDomain}/innerapi/flow/cr:close`,{
        "buildNumber": params.buildNumber,
        "pipelineId": params.pipelineID,
    },{
        headers: {
            'Cookie': params.appStackCookie,
            "X-Operator-Id": params.appStackUserId,
            "X-Tenant-Id": params.appStackOrgId,
            "caller_name": "flowstep",
            "caller-name": "flowstep",
            "timestamp": params.appStackCloudRolloutTimeStamp,
            "token": params.appStackCloudRolloutToken
        }
    })

    step.debug(`close_change_request_response=${response}`)

    step.info(`close_change_request_result=${response.statusText}`)

    if( response.status !== 200){
        throw new Error(`close_change_request failed`)
    }

}

runStep()
    .then(function() {
        step.success('run step successfully!')
    })
    .catch(function(err: Error) {
        step.error(err.message)
        process.exit(-1)
    })
